//
//  GailanPagerVc.m
//  ainkjj
//
//  Created by MAX on 2020/11/10.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "GailanPagerVc.h"
#import "GetNavList_res.h"
// 定位处理
#import "LzyLocationManager.h"
#import "GetThisWeather_res.h"

typedef enum : NSUInteger {
    LocationFlagOk,
    LocationFlagRestrict,
    LocationFlagUnknow,
} LocationFlag;

@interface GailanPagerVc ()
@property (nonatomic, strong)NSMutableArray *titlesArr;
@property (nonatomic, strong)NSMutableArray *classNamesArr;
@property (nonatomic, strong)GetNavList_res *getNavList;

//定位
@property (nonatomic, copy) NSString *lat;
@property (nonatomic, copy) NSString *lng;
@property (nonatomic, assign)LocationFlag mylocationFlag;
/** 地理编码管理器 */
@property (nonatomic, strong) CLGeocoder *geoC;

@property (nonatomic, strong)QMUIButton *locationBtn;
@property (nonatomic, strong)UILabel *wenduLb;
@property (nonatomic, strong)UIImageView *tianqi_icon_iv;
@property (nonatomic, strong)UILabel *diqu_lb ;
@end

@implementation GailanPagerVc
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
- (instancetype)init{
    self =  [super init];
    if (self) {
        
        
        //
        //        self.showOnNavigationBar = YES;
        self.titleColorSelected = rgba(17,17,17,1);
        self.titleColorNormal = rgba(153,153,153,1);
        self.titleSizeNormal = 16;
        self.titleSizeSelected = 20;
        [self setMenuViewLayoutMode:WMMenuViewLayoutModeLeft];
        
        self.titleFontName = @"PingFangSC-Semibold";
        self.automaticallyCalculatesItemWidths = YES;
        self.itemMargin = 20;
        [self setMenuViewStyle:WMMenuViewStyleDefault];
        
        //        self.fabuItem = [[UIBarButtonItem alloc] initWithImage:UIImageMake(@"issue_icon") style:UIBarButtonItemStylePlain target:self action:@selector(xxx_action)];
        //        [self setMenuViewStyle:WMMenuViewStyleLine];
        
        //        self.menuView.rightView = self.fabuItem;
        self.titleLb_maxY = 44;
        if (Lzy_StatusBarAndNavigationBarHeight == 64) {
            self.titleLb_maxY = 24;
        }
        
        self.keys = @[@"category_id", @"category_id"].mutableCopy;
        self.values = @[@"1", @"0"].mutableCopy;
        
        
        
        
        // 天气按钮
        
        //    self.locationBtn = [[QMUIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 140, 54, 120, 44)];
        ////    [self.sv addSubview:self.locationBtn];
        //    [self.locationBtn setTitle:@"章贡区" forState:UIControlStateNormal];
        //    [self.locationBtn setImagePosition:QMUIButtonImagePositionTop];
        //    [self.locationBtn setImage:UIImageMake(@"cloudy_icon") forState:UIControlStateNormal];
        //    self.locationBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        UIImageView *tianqi_icon_iv = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth - 110, self.titleLb_maxY - 16, 37, 32)];
        [self.view addSubview:tianqi_icon_iv];
        self.tianqi_icon_iv = tianqi_icon_iv;
        
        UILabel *wenduLb = [[UILabel alloc] initWithFrame:CGRectMake( CGRectGetMaxX(tianqi_icon_iv.frame)+ 4, CGRectGetMinY(tianqi_icon_iv.frame) + 12, 80, 20)];
        [self.view addSubview:wenduLb];
        self.wenduLb = wenduLb;
        wenduLb.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12.0f];
        wenduLb.textColor = [UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0f];
        wenduLb.text = @"";
        
        UILabel *diqu_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(tianqi_icon_iv.frame), CGRectGetMaxY(tianqi_icon_iv.frame), 120, 20)];
        [self.view addSubview:diqu_lb];
        diqu_lb.textColor = rgb(102,102,102);
        diqu_lb.font = UIFontMake(14);
        self.diqu_lb = diqu_lb;
        
        
        // 定位开启
        [self checkLocation];
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self reqCat];

}
- (void)reqCat{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [PPHTTPRequest req:@"api/app/getNavList" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            GetNavList_res *model = [GetNavList_res mj_objectWithKeyValues:response];
            if (model.data.list > 0) {
                self.getNavList = model;
                NSMutableArray *titlesArr = NSMutableArray.new;
                NSMutableArray *keysArr = NSMutableArray.new;
                NSMutableArray *valuesArr = NSMutableArray.new;
                NSMutableArray *clsNameArr = NSMutableArray.new;

                for (NSInteger i = 0; i < model.data.list.count; i++) {
                    GetNavList_resList *m = model.data.list[i];
                    [titlesArr addObject:m.name];
                    if ([m.name isEqualToString:@"智能婴儿床"]) {
                        [clsNameArr addObject:@"Gailan_vc"];
                    }else if ([m.name isEqualToString:@"智能宠物柜"]){
                        [clsNameArr addObject:@"Cwg_ganlan_vc"];
                    }
                    [keysArr addObject:@"category_id"];
                    [valuesArr addObject:m.category_id];
                }
                self.titlesArr = titlesArr;
                self.classNamesArr = clsNameArr;
                self.keys = keysArr;
                self.values = valuesArr;
                [self reloadData];

            }
        }
        
        else{
            [QMUITips showError:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
}
- (NSMutableArray *)titlesArr{
    if(_titlesArr == nil)
    { _titlesArr = @[@"婴儿床", @"宠物柜"].mutableCopy;
    }
    
    return _titlesArr;
}
- (NSMutableArray *)classNamesArr{
    if(_classNamesArr == nil)
    {_classNamesArr = @[ @"Gailan_vc", @"Gailan_vc"].mutableCopy;
    }
    
    return _classNamesArr;
}
#pragma mark - WMPageController DataSource
- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    return self.titlesArr.count;
}

- (NSString *)pageController:(WMPageController *)pageController titleAtIndex:(NSInteger)index {
    return self.titlesArr[index];
}

- (UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    UIViewController *vc = nil;
    vc = [NSClassFromString(self.classNamesArr[index]) new];
    
    return vc;
}

- (CGRect)pageController:(WMPageController *)pageController preferredFrameForMenuView:(WMMenuView *)menuView {
    
    CGFloat leftMargin =  0;
    CGFloat originY = self.titleLb_maxY  ;
    return CGRectMake(leftMargin, originY, ScreenWidth - 110, 44);
}

- (CGRect)pageController:(WMPageController *)pageController preferredFrameForContentView:(WMScrollView *)contentView {
    
    CGFloat originY = CGRectGetMaxY([self pageController:pageController preferredFrameForMenuView:self.menuView]) ;
    
    return CGRectMake(0, originY, self.view.frame.size.width, self.view.frame.size.height - originY - Lzy_TabbarHeight);
}
- (void)req_tianqi{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:self.lat forKey:@"lat"];
    [dict setObject:self.lng forKey:@"lon"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"java/app/weather/getThisWeather" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            /*
             {
             "error_msg": "操作成功",
             "data": {
             "name": "章贡区",
             "updatetime": "2020-04-24 17:50:08",
             "condition": "多云",
             "temp": "20"
             },
             "error_code": 0
             }
             */
            
            GetThisWeather_res *res = [GetThisWeather_res mj_objectWithKeyValues:response];
            
            
            
            
            self.wenduLb.text = [NSString stringWithFormat:@"%@ %@℃", [Anktool strBlankHolder:res.data.condition], [Anktool strBlankHolder:res.data.temp]];
            //            [self.locationBtn setTitle:response[@"data"][@"name"] forState:UIControlStateNormal];
            self.diqu_lb.text = [Anktool strBlankHolder:res.data.name];
            NSString *condition = res.data.condition;
            NSArray *conArr = @[@"晴", @"雨", @"阴", @"雪",];
            if ([conArr indexOfObject:condition] != NSNotFound) {
                self.tianqi_icon_iv.image = UIImageMake(condition);
                self.tianqi_icon_iv.bounds = CGRectMake(0, 0, self.tianqi_icon_iv.image.size.width, self.tianqi_icon_iv.image.size.height);
            }else{
                self.tianqi_icon_iv.image = UIImageMake(@"阴");;
            }
            self.tianqi_icon_iv.frame = CGRectMake(self.tianqi_icon_iv.mj_origin.x, self.tianqi_icon_iv.mj_origin.y, self.tianqi_icon_iv.image.size.width, self.tianqi_icon_iv.image.size.height);
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"]];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
    
}

#pragma mark - ================== 定位 ==================
- (void)checkLocation{
    //只获取一次
    __block  BOOL isOnece = YES;
    [LzyLocationManager getLzyLocationWithSuccess:^(double lat, double lng){
        isOnece = NO;
        //只打印一次经纬度
        DLog(@"lat lng (%f, %f)", lat, lng);
        
        if (!isOnece) {
            [LzyLocationManager stop];
        }
        if (self.lat.length > 0 || self.lng.length > 0) {
            self.mylocationFlag = 0;
            
            self.lat = @(lat).stringValue;
            self.lng = @(lng).stringValue;
            
            // 请求天气数据
            [self req_tianqi];
        }else{
            
            self.lat = @(lat).stringValue;
            self.lng = @(lng).stringValue;
        }
        
        
        CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
        //        location = [[CLLocation alloc] initWithLatitude:39.90960456049752 longitude:116.3972282409668];
        
        [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark *pl = [placemarks firstObject];
            
            if(error == nil)
            {
                DLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);
                
                DLog(@"%@", pl.addressDictionary);
                //
                //                self.selectedAddressArr = @[@{@"cityName" : pl.addressDictionary[@"State"]}, @{@"cityName" : pl.addressDictionary[@"City"]}];
                //                NSMutableString *string = [NSMutableString string];
                //                for (NSDictionary *dict in self.selectedAddressArr) {
                //                    [string appendFormat:@"%@ ",dict[@"cityName"]];
                //                }
                //                self.releseview.addressTF.text = string;
                //                self.location = pl.addressDictionary[@"City"];
                //                [self->locationBtn setTitle:[NSString stringWithFormat:@"%@▽",self.location] forState:UIControlStateNormal];
                
            }else{
                DLog(@"%@", error);
            }
        }];
        
    } Failure:^(NSError *error){
        self.lat = @"";
        self.lng = @"";
        isOnece = NO;
        DLog(@"error = %@", error);
        if ([error code] == kCLErrorDenied || [error code] == kCLErrorRegionMonitoringDenied) {
            DLog(@"定位权限被限制");
            self.mylocationFlag = 1;
            self.diqu_lb.text = @"定位权限被限制";
        }
        if ([error code] == kCLErrorLocationUnknown) {
            DLog(@"无法获取位置信息");
            self.mylocationFlag = 2;
            self.diqu_lb.text = @"无法获取位置信息";
        }
        
        
        if (!isOnece) {
            [LzyLocationManager stop];
        }
        //        [SVProgressHUD showErrorWithStatus:@"无法获取位置"];
        
    }];
    //    //一直持续获取定位则
    //    [LzyLocationManager getLzyLocationWithSuccess:^(double lat, double lng){
    //        //不断的打印经纬度
    //        NSLog(@"lat lng (%f, %f)", lat, lng);
    //    } Failure:^(NSError *error){
    //        NSLog(@"error = %@", error);
    //    }];
}
/** 地理编码管理器 */
- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}
@end
